package com.example.yblin.hello24;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yblin.hello24.DataUtils.GameUtil;
import com.example.yblin.hello24.DataUtils.NetUtil;

public class GameActivity extends AppCompatActivity implements View.OnClickListener, PopupMenu.OnMenuItemClickListener {

    private TextView btNum1;
    private TextView btNum2;
    private TextView btNum3;
    private TextView btNum4;
    private TextView btAdd;
    private TextView btSubtract;
    private TextView btMultiply;
    private TextView btDivide;
    private TextView btLeftBracket;
    private TextView btRightBracket;
    private TextView tvExpression;
    private TextView reinput;
    private TextView submitAll;
    private PopupMenu popupMenu;
    private TextView tvPopupMenu;
    private ImageView btQuestionLeft;
    private ImageView btQuestionRight;
    private TextView btBackspace;
    private int page = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        btNum1 = findViewById(R.id.textView_num1);
        btNum1.setOnClickListener(this);
        btNum2 = findViewById(R.id.textView_num2);
        btNum2.setOnClickListener(this);
        btNum3 = findViewById(R.id.textView_num3);
        btNum3.setOnClickListener(this);
        btNum4 = findViewById(R.id.textView_num4);
        btNum4.setOnClickListener(this);


        btAdd = findViewById(R.id.textView_add);
        btAdd.setOnClickListener(this);
        btSubtract = findViewById(R.id.textView_subtract);
        btSubtract.setOnClickListener(this);
        btMultiply = findViewById(R.id.textView_multiply);
        btMultiply.setOnClickListener(this);
        btDivide = findViewById(R.id.textView_divide);
        btDivide.setOnClickListener(this);
        btLeftBracket = findViewById(R.id.textView_left_bracket);
        btLeftBracket.setOnClickListener(this);
        btRightBracket = findViewById(R.id.textView_right_bracket);
        btRightBracket.setOnClickListener(this);

        tvExpression = findViewById(R.id.textView_expression);
        reinput = findViewById(R.id.textView_reinput);
        reinput.setOnClickListener(this);
        submitAll = findViewById(R.id.textView_submit_all);
        submitAll.setOnClickListener(this);
        tvPopupMenu = findViewById(R.id.textView_pop_up_menu);
        tvPopupMenu.setOnClickListener(this);

        btQuestionLeft = findViewById(R.id.button_question_left);
        btQuestionLeft.setOnClickListener(this);
        btQuestionRight = findViewById(R.id.button_question_right);
        btQuestionRight.setOnClickListener(this);
        btBackspace = findViewById(R.id.textView_backspace);
        btBackspace.setOnClickListener(this);
        getPageData(page);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textView_num1:
                if (!GameUtil.numbers[page][0].selected) {//在数字没有被选中的前提下
                    GameUtil.numbers[page][0].selected = true;//数字被选中
                    GameUtil.expression[page].add(GameUtil.numbers[page][0].number);//数字被添加进表达式
                    btNum1.setAlpha(0.5f);//UI设置被选中
                }//数字被选中无响应
                break;
            case R.id.textView_num2:
                if (!GameUtil.numbers[page][1].selected) {//在数字没有被选中的前提下
                    GameUtil.numbers[page][1].selected = true;//数字被选中
                    GameUtil.expression[page].add(GameUtil.numbers[page][1].number);//数字被添加进表达式
                    btNum2.setAlpha(0.5f);//UI设置被选中
                    //tvExpression.setText(GameUtil.toString(GameUtil.expression[page]));//UI表达式刷新
                }//数字被选中无响应
                break;
            case R.id.textView_num3:
                if (!GameUtil.numbers[page][2].selected) {//在数字没有被选中的前提下
                    GameUtil.numbers[page][2].selected = true;//数字被选中
                    GameUtil.expression[page].add(GameUtil.numbers[page][2].number);//数字被添加进表达式
                    btNum3.setAlpha(0.5f);//UI设置被选中
                }//数字被选中无响应
                break;
            case R.id.textView_num4:
                if (!GameUtil.numbers[page][3].selected) {//在数字没有被选中的前提下
                    GameUtil.numbers[page][3].selected = true;//数字被选中
                    GameUtil.expression[page].add(GameUtil.numbers[page][3].number);//数字被添加进表达式
                    btNum4.setAlpha(0.5f);//UI设置被选中
                }//数字被选中无响应
                break;
            case R.id.textView_add:
                GameUtil.expression[page].add(GameUtil.ADD);
                break;
            case R.id.textView_subtract:
                GameUtil.expression[page].add(GameUtil.SUB);
                break;
            case R.id.textView_multiply:
                GameUtil.expression[page].add(GameUtil.MUL);
                break;
            case R.id.textView_divide:
                GameUtil.expression[page].add(GameUtil.DIV);
                break;
            case R.id.textView_left_bracket:
                GameUtil.expression[page].add(GameUtil.LEFT);
                break;
            case R.id.textView_right_bracket:
                GameUtil.expression[page].add(GameUtil.RIGHT);
                break;
            case R.id.textView_reinput:
                GameUtil.expression[page].clear();//表达式清空
                GameUtil.numbers[page][0].selected = false;//数字全不选中
                GameUtil.numbers[page][1].selected = false;
                GameUtil.numbers[page][2].selected = false;
                GameUtil.numbers[page][3].selected = false;
                btNum1.setAlpha(1);
                btNum2.setAlpha(1);
                btNum3.setAlpha(1);
                btNum4.setAlpha(1);
                //R
                break;
            case R.id.textView_submit_all:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("确认提交")
                        .setMessage("你真的要提交吗？")
                        .setPositiveButton("提交", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                new GameEndAsync().execute();
                                submitAll.setEnabled(false);
                            }
                        })
                        .setNegativeButton("不提交", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                            }
                        });
                AlertDialog dialog = builder.create();
                dialog.show();

                break;
            case R.id.textView_pop_up_menu:
                popupMenu = new PopupMenu(this, tvPopupMenu);
                Menu menu = popupMenu.getMenu();
                for (int i = 1; i <= 10; i++) {
                    menu.add(0, i, 0, "第" + i + "题");
                }
                //popupMenu.getMenuInflater().inflate(R.menu.menu_page,popupMenu.getMenu());
                popupMenu.setOnMenuItemClickListener(this);
                popupMenu.show();
                break;
            case R.id.button_question_left:
                if (page > 1) {
                    getPageData(page - 1);
                }
                break;
            case R.id.button_question_right:
                if (page < 10) {
                    getPageData(page + 1);
                }
                break;
            case R.id.textView_backspace:
                if (GameUtil.expression[page].size() > 0) {
                    int index = GameUtil.expression[page].size() - 1;
                    int num = GameUtil.expression[page].get(index);
                    if (num != GameUtil.ADD && num != GameUtil.SUB
                            && num != GameUtil.MUL && num != GameUtil.DIV
                            && num != GameUtil.LEFT && num != GameUtil.RIGHT) {
                        for (int i = 0; i < 4; i++) {
                            if (GameUtil.numbers[page][i].number == num && GameUtil.numbers[page][i].selected) {//如果被删除的数字被选中
                                GameUtil.numbers[page][i].selected = false;//数字取消选中
                                switch (i) {
                                    case 0:
                                        btNum1.setAlpha(1);
                                        break;
                                    case 1:
                                        btNum2.setAlpha(1);
                                        break;
                                    case 2:
                                        btNum3.setAlpha(1);
                                        break;
                                    case 3:
                                        btNum4.setAlpha(1);
                                        break;
                                }
                                break;
                            }
                        }
                    }
                    GameUtil.expression[page].remove(index);
                }
                break;
        }
        tvExpression.setText(GameUtil.toString(GameUtil.expression[page], GameUtil.USAGE_FOR_SHOW));//UI表达式刷新
    }

    @Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确认退出？")
                .setMessage("你真的要退出吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        GameActivity.super.onBackPressed();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @Override
    public boolean onMenuItemClick(MenuItem menuItem) {
        int pageId = menuItem.getItemId();
        getPageData(pageId);
        return true;
    }

    public void getPageData(int pageId) {
        page = pageId;
        tvPopupMenu.setText("第" + page + "题");
        //btNum1.setText("" + GameUtil.numbers[pageId][0].number);
        int number = 0;
        number = (GameUtil.numbers[page][0].number - 1) * 4 + ((int) (Math.random() * 4));//获取牌面数字，乘以4后得到黑桃+牌面数字，加0-3得到随机4色
        btNum1.setBackground(getDrawable(GameUtil.poker[number]));
        if (GameUtil.numbers[page][0].selected) {
            btNum1.setAlpha(0.5f);
        } else {
            btNum1.setAlpha(1);
        }

        number = (GameUtil.numbers[page][1].number - 1) * 4 + ((int) (Math.random() * 4));//获取牌面数字，乘以4后得到黑桃+牌面数字，加0-3得到随机4色
        btNum2.setBackground(getDrawable(GameUtil.poker[number]));
        if (GameUtil.numbers[page][1].selected) {
            btNum2.setAlpha(0.5f);
        } else {
            btNum2.setAlpha(1);
        }

        number = (GameUtil.numbers[page][2].number - 1) * 4 + ((int) (Math.random() * 4));//获取牌面数字，乘以4后得到黑桃+牌面数字，加0-3得到随机4色
        btNum3.setBackground(getDrawable(GameUtil.poker[number]));
        if (GameUtil.numbers[page][2].selected) {
            btNum3.setAlpha(0.5f);
        } else {
            btNum3.setAlpha(1);
        }

        number = (GameUtil.numbers[page][3].number - 1) * 4 + ((int) (Math.random() * 4));//获取牌面数字，乘以4后得到黑桃+牌面数字，加0-3得到随机4色
        btNum4.setBackground(getDrawable(GameUtil.poker[number]));
        if (GameUtil.numbers[page][3].selected) {
            btNum4.setAlpha(0.5f);
        } else {
            btNum4.setAlpha(1);
        }

        tvExpression.setText(GameUtil.toString(GameUtil.expression[page], GameUtil.USAGE_FOR_SHOW));
    }


    public class GameEndAsync extends AsyncTask<Void, Void, Integer> {
        @Override
        protected Integer doInBackground(Void... voids) {
            return GameUtil.end(GameActivity.this);
        }

        @Override
        protected void onPostExecute(Integer result) {
            submitAll.setEnabled(true);
            if (result == NetUtil.CODE_OK) {
                AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this);
                builder.setTitle("游戏结果")
                        .setMessage("总答题数：10\n正确数：" + GameUtil.correctNumber + '\n'
                                + "正确率：" + GameUtil.correctNumber * 10 + "%\n"
                                + "耗时：" + GameUtil.costtime + "秒")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                startActivity(new Intent(GameActivity.this, ResultActivity.class));
                                GameActivity.this.finish();
                            }
                        });
                builder.setCancelable(false);

                AlertDialog dialog = builder.create();
                dialog.show();

            } else if (result == NetUtil.CODE_USERNAME_OR_PASSWORD_ERROR || result == NetUtil.CODE_CONNECTION_ERROR) {
                Toast.makeText(GameActivity.this, "提交失败，请检查网络并重新提交！", Toast.LENGTH_LONG).show();
            } else if (result > 10000) {
                result -= 10000;//获得非法表达式序号
                Toast.makeText(GameActivity.this, "问题" + result + "中的表达式输入错误！", Toast.LENGTH_LONG).show();
            }
        }
    }
}
